import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Weather, City, WeatherForecast, ApiResponse } from '@/types'
import { weatherApi } from '@/api/weather'
import { ElMessage } from 'element-plus'
import { useAppConfigStore } from './appConfig'

interface WeatherCache {
  [city: string]: {
    data: Weather
    timestamp: number
  }
}

export const useWeatherStore = defineStore('weather', () => {
  // 状态
  const currentWeather = ref<Weather | null>(null)
  const weatherForecast = ref<WeatherForecast[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const searchHistory = ref<string[]>([])
  const cityList = ref<City[]>([])
  const weatherCache = ref<WeatherCache>({})
  
  // 获取应用配置
  const appConfig = useAppConfigStore()
  
  // 缓存有效期（5分钟）
  const CACHE_DURATION = 5 * 60 * 1000
  
  // 计算属性：转换后的当前天气
  const displayWeather = computed(() => {
    if (!currentWeather.value) return null
    
    const weather = { ...currentWeather.value }
    
    // 温度单位转换
    if (appConfig.temperatureUnit !== weather.temperatureUnit) {
      if (appConfig.temperatureUnit === 'F') {
        weather.temperature = (weather.temperature * 9/5) + 32
      } else {
        weather.temperature = (weather.temperature - 32) * 5/9
      }
      weather.temperatureUnit = appConfig.temperatureUnit
    }
    
    return weather
  })
  
  // 检查缓存
  const checkCache = (city: string): Weather | null => {
    const cached = weatherCache.value[city]
    if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
      return cached.data
    }
    return null
  }
  
  // 获取天气
  const fetchWeather = async (city: string): Promise<Weather | null> => {
    // 检查缓存
    const cached = checkCache(city)
    if (cached) {
      currentWeather.value = cached
      updateSearchHistory(city)
      return cached
    }
    
    loading.value = true
    error.value = null
    
    try {
      const response = await weatherApi.getCurrentWeather(city)
      
      if (response.success && response.data) {
        currentWeather.value = response.data
        
        // 更新缓存
        weatherCache.value[city] = {
          data: response.data,
          timestamp: Date.now()
        }
        
        // 更新搜索历史
        updateSearchHistory(city)
        
        return response.data
      } else {
        error.value = response.error || '获取天气失败'
        ElMessage.error(error.value!)
        return null
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取天气失败'
      ElMessage.error(error.value)
      return null
    } finally {
      loading.value = false
    }
  }
  
  // 获取天气预报
  const fetchWeatherForecast = async (city: string): Promise<WeatherForecast[]> => {
    try {
      const response = await weatherApi.getWeatherForecast(city)
      
      if (response.success && response.data) {
        weatherForecast.value = response.data
        return response.data
      } else {
        ElMessage.error(response.error || '获取天气预报失败')
        return []
      }
    } catch (err) {
      ElMessage.error('获取天气预报失败')
      return []
    }
  }
  
  // 搜索城市
  const searchCities = async (query: string): Promise<City[]> => {
    try {
      const response = await weatherApi.searchCities(query)
      
      if (response.success && response.data) {
        cityList.value = response.data
        return response.data
      } else {
        return []
      }
    } catch (err) {
      console.error('搜索城市失败:', err)
      return []
    }
  }
  
  // 更新搜索历史
  const updateSearchHistory = (city: string) => {
    // 移除重复项
    searchHistory.value = searchHistory.value.filter(c => c !== city)
    
    // 添加到开头
    searchHistory.value.unshift(city)
    
    // 限制历史记录数量
    if (searchHistory.value.length > 10) {
      searchHistory.value = searchHistory.value.slice(0, 10)
    }
    
    // 持久化到localStorage
    localStorage.setItem('weatherSearchHistory', JSON.stringify(searchHistory.value))
  }
  
  // 加载搜索历史
  const loadSearchHistory = () => {
    const saved = localStorage.getItem('weatherSearchHistory')
    if (saved) {
      searchHistory.value = JSON.parse(saved)
    }
  }
  
  // 清除缓存
  const clearCache = () => {
    weatherCache.value = {}
  }
  
  // 清除错误
  const clearError = () => {
    error.value = null
  }
  
  // 清除当前天气
  const clearWeather = () => {
    currentWeather.value = null
    weatherForecast.value = []
  }
  
  // 初始化
  loadSearchHistory()
  
  return {
    // 状态
    currentWeather,
    weatherForecast,
    loading,
    error,
    searchHistory,
    cityList,
    
    // 计算属性
    displayWeather,
    
    // 方法
    fetchWeather,
    fetchWeatherForecast,
    searchCities,
    clearCache,
    clearError,
    clearWeather
  }
}) 